package bfa.cps;




import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import volumeControl.VolumeControl;
import volumeControl.VolumeControl.VolumeChangeListener;
import bfa.cps.connectivity.ConnectivityReceiver;
import bfa.cps.Preferences;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;

import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CountrypowerstationradioActivity extends Activity  implements  OnClickListener,VolumeChangeListener {
	private static ConnectivityReceiver receiver = null;

	private TextView imageViewConnectivity,textViewSong,textViewTitle;
	//private TextView sourceTextView;
	private ImageView copertina;
	
    private SeekBar volumeSeekBar;
    private boolean volumeSeekBarBeingAdjusted = false;

	static Intent playbackServiceIntent;
	
	private Button buttonPlay,buttonStop;
	
	
	private static BackgroundAudioService myService;
	
	private void configureVolumeManager() {
		if (myService!=null) {
			if (myService.getPlayer()!=null) {
				// The following three lines are all that is needed to use the VolumeControl class		
				VolumeControl.sharedVolumeControl().configure(myself, myService.getPlayer());
		        VolumeControl.sharedVolumeControl().addVolumeChangeListener(myself);
		        VolumeControl.sharedVolumeControl().startVolumeMonitor(); // this needed iff a  callback is desired when the system volume is changed (to update a volume level SeekBar for example)
			}
		        
		}
	}

    final CountrypowerstationradioActivity myself=this;
    
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {
        
    	
    	@Override
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 @SuppressWarnings("unchecked")
     		 LocalBinder<BackgroundAudioService> binder = (LocalBinder<BackgroundAudioService>) service;             
             myService = binder.getService();
             getPrefs();
             myService.setHandler(new MyHandler());
         	//myService.setSomeBodyListening(true);
             
          
             configureVolumeManager();
             
             
        }
        
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            stopService(playbackServiceIntent);
        }
    	
    };

    
    private void initializeUIElements() {

//        playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
//        playSeekBar.setMax(100);
//        playSeekBar.setVisibility(View.INVISIBLE);
//
        buttonPlay = (Button) findViewById(R.id.buttonPlay);
        buttonPlay.setOnClickListener(this);

        buttonStop = (Button) findViewById(R.id.buttonStopPlay);
        buttonStop.setEnabled(false);
        buttonStop.setOnClickListener(this);
//
//        buttonRecord = (Button) findViewById(R.id.buttonRecord);
//        buttonRecord.setOnClickListener(this);
//
//        buttonStopRecord = (Button) findViewById(R.id.buttonStopRecord);
//        buttonStopRecord.setOnClickListener(this);
//        
        //sourceTextView=(TextView) findViewById(R.id.sourceTV);
//        songInfoTextView=(TextView) findViewById(R.id.songInfo);
    	
        textViewSong=(TextView) findViewById(R.id.textViewSong);
        textViewTitle=(TextView) findViewById(R.id.textViewTitle);
        //textViewHtml=(TextView) findViewById(R.id.textViewHtml);
        copertina=(ImageView)findViewById(R.id.imageCopertina);
        
        volumeSeekBar = (SeekBar)this.findViewById(R.id.volumeSeekBar);
        volumeSeekBar.setOnSeekBarChangeListener(
        		new OnSeekBarChangeListener() {
        			@Override
        			public void onStopTrackingTouch(SeekBar seekBar) {
                        volumeSeekBarBeingAdjusted = false;
        			}
        			@Override
        			public void onStartTrackingTouch(SeekBar seekBar) {
        				 volumeSeekBarBeingAdjusted = true;
        			}
        			
        			@Override
        			public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
        				// if (fromUser) {
                        VolumeControl.sharedVolumeControl().setVolume((float) ((float)progress/100.));
        			}
        		}
		);        
        
        
        
        
    	imageViewConnectivity=(TextView) findViewById(R.id.textViewConnectivity);
    	setNetworkImageIcon(connectionStatus);
    }
    
    private void sistemaBottoni() {
    	if (myService!=null) {
      	  	boolean sip=myService.isPlaying();
        	buttonPlay.setEnabled(! sip);
    		buttonStop.setEnabled(sip);

    		textViewSong.setText(myService.getNewSong());
    		textViewTitle.setText(myService.getNewTitle());

        }
    }
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initializeUIElements();
        
        
        getPrefs();
        
        if (notificationManager!=null) {
        	notificationManager.cancel(Constants.NOTIFICATION_ID);
        	notificationManager=null;
        }
        	
        
        if (playbackServiceIntent==null) {
        	playbackServiceIntent=new Intent(this, BackgroundAudioService.class);
            startService(playbackServiceIntent);
            //playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
            bindService(playbackServiceIntent, mConnection, Context.BIND_AUTO_CREATE);            
        }

        
        
        if (receiver==null) {
            receiver = new ConnectivityReceiver();
            receiver.handler=new MyHandler();
        }

//        if (myService!=null) {
//        	buttonPlay.setEnabled(! myService.isPlaying());
//    		buttonStop.setEnabled(myService.isPlaying());
//
//    		textViewSong.setText(myService.getNewSong());
//    		textViewTitle.setText(myService.getNewTitle());
//
//        }
        
        
        
    }
    
    @Override
    protected void onStart() {    	
    	super.onStart();
    	
		//getPrefs();
		
		sistemaBottoni();
		configureVolumeManager();
		
		if (myService!=null) {
			myService.enableSongListCheker();			
		}

		
    }
    
    
    @Override
    public void onResume() {
      super.onResume();
      sistemaBottoni();
      configureVolumeManager();
      
      if (copertina!=null && lastDrawable!=null) {
    	  copertina.setImageDrawable(lastDrawable);
      }
      
      registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    
    @Override
    public void onPause() {
      super.onPause();
            
      unregisterReceiver(receiver);     
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	try {
    		unbindService(mConnection);
    	} catch (Exception e) {}
    }
    
    
    static Drawable lastDrawable=null;
    private void scaricaCopertina(String posCopertina) {
    	if (posCopertina!=null && (!posCopertina.equals(""))) {
    		InputStream URLcontent;
			try {
				URLcontent = (InputStream) new URL(posCopertina).getContent();
				lastDrawable=Drawable.createFromStream(URLcontent, "copertina");
				copertina.setImageDrawable(lastDrawable);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
    private String lastCopertina="";
    @SuppressLint("HandlerLeak")
	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			Bundle bundle = msg.getData();
			
			
			if (bundle.containsKey(ConnectivityReceiver.CR_KEY)) {
				String value = bundle.getString(ConnectivityReceiver.CR_KEY);
				setNetworkImageIcon(value);
				//Toast.makeText(getApplicationContext(), "Fix acquired in "+value+" sec.", Toast.LENGTH_SHORT).show();
				
			}
			
			if (bundle.containsKey("player")) {
				String value = bundle.getString("player");
				Log.i("player", value);
				
				if (value.equals("onPrepared")) {
					buttonPlay.setEnabled(false);
					buttonStop.setEnabled(true);
				}
				
//				if (mService!=null) {
//					if (pv.isHasFix()!=mService.hasFix) {
//												
//						pv.setHasFix(mService.hasFix);
//						pv.invalidate();
//					}					
//				}
			}
			
			if (bundle.containsKey("song")) {
				String value = bundle.getString("song");
				textViewSong.setText(value);
				
				if (contentView!=null) {
					contentView.setTextViewText(R.id.custom_view_song, value);
				}
				
			}
			if (bundle.containsKey("title")) {
				String value = bundle.getString("title");
				textViewTitle.setText(value);

				if (contentView!=null) {
					addCustomNotification();
					
					contentView.setTextViewText(R.id.custom_view_title, value);					
				}
			}
			if (bundle.containsKey("copertina")) {
				String value = bundle.getString("copertina");
				if (! value.equals(lastCopertina)) {
					scaricaCopertina(value);

					lastCopertina=value;
				}
	        	
				
			}
			
			
			
			if (bundle.containsKey("TelephonyManager")) {
				String value = bundle.getString("TelephonyManager");
				
				if (value.equals("CALL_STATE_RINGING")) {
					
				}
				if (value.equals("CALL_STATE_IDLE")) {
					buttonPlay.setEnabled(false);
					buttonStop.setEnabled(true);					
				}
				if (value.equals("CALL_STATE_OFFHOOK")) {
					
				}
			}

			
		}
	}
    
    private static String connectionStatus=ConnectivityReceiver.CR_UNKNOWN;
    private void setNetworkImageIcon(String connectionStatus) {
    	CountrypowerstationradioActivity.connectionStatus=connectionStatus;
    	
    	if (connectionStatus.equals(ConnectivityReceiver.CR_CONNECTED)) {
			//imageViewConnectivity.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.circle_green, 0);
    		imageViewConnectivity.setText(R.string.ok);
    		imageViewConnectivity.setTextColor(Color.rgb(0, 0x80, 0));
    		//buttonPlay.setEnabled(true);
    		sistemaBottoni();
    		
    		
    	} else if (
    			connectionStatus.equals(ConnectivityReceiver.CR_SUSPENDED)
    			|| connectionStatus.equals(ConnectivityReceiver.CR_UNKNOWN)
    			|| connectionStatus.equals(ConnectivityReceiver.CR_DISCONNECTING)
    			|| connectionStatus.equals(ConnectivityReceiver.CR_CONNECTING)
		) {
			//imageViewConnectivity.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.circle_gray, 0);
    		imageViewConnectivity.setText(R.string.unsknown);
    		imageViewConnectivity.setTextColor(Color.GRAY);
			buttonPlay.setEnabled(false);
		} else {
			//imageViewConnectivity.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.circle_red, 0);
			imageViewConnectivity.setText(R.string.error);
			imageViewConnectivity.setTextColor(Color.RED);
			buttonPlay.setEnabled(false);
		}
		
    	imageViewConnectivity.refreshDrawableState();
		imageViewConnectivity.invalidate();
    }



	@Override
	public void onClick(View v) {
		if (v == buttonPlay) {
			myService.startPlaying();			
			buttonPlay.setEnabled(false);
			buttonStop.setEnabled(true);
			
	    } else if (v == buttonStop) {
	    	myService.stopPlaying();
	    	
			buttonPlay.setEnabled(true);
			buttonStop.setEnabled(false);
	    	
//	    } else if (v == buttonRecord) {
//	        recorderThread = new RecorderThread();
//	        recorderThread.start();
//	
//	        buttonRecord.setEnabled(false);
//	        buttonStopRecord.setEnabled(true);
//	    } else if (v == buttonStopRecord) {
//	        stopRecording();
	    }
	}
    
	@Override
	public void onBackPressed() {
		if (! myService.isPlaying()) {
			// Stop the activity
			myService.stopPlaying();
			CountrypowerstationradioActivity.super.onBackPressed();
			
	    	try {
	    		unbindService(mConnection);
	    		stopService(playbackServiceIntent);
	    	} catch (Exception e) {}
			myService.disableSongListCheker();
			myService.stopAll();
		} else {
			addCustomNotification();
			moveTaskToBack(true);
		}
	}

	
	Notification notification = null;
	RemoteViews contentView = null;
	static NotificationManager notificationManager=null;
	
    private void addCustomNotification(){
    	notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	
    	
    	
    	int icon = R.drawable.cps_launcher;
    	CharSequence text = "Country Power Station";
    	long when = System.currentTimeMillis();
    	//long[] vibrate = {0,100,200,300};
    	
    	notification = new Notification(icon,text,when);
    	Intent notificationIntent = new Intent(this, CountrypowerstationradioActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    	//Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
    					   
    	
    	contentView = new RemoteViews(getPackageName(), R.layout.customlayout);
    	
    	contentView.setTextViewText(R.id.custom_view_song, textViewSong.getText());
    	contentView.setTextViewText(R.id.custom_view_title, textViewTitle.getText());
    	//contentView.setProgressBar(R.id.custom_view_progress, Constants.PROGRESS_MAX, 0, false);
    	contentView.setImageViewResource(R.id.custom_view_image, R.drawable.cps_launcher);
    	
    	notification.flags |= Notification.FLAG_AUTO_CANCEL;
    	notification.contentView = contentView;
    	notification.contentIntent = contentIntent;

    	//notification.vibrate = vibrate;
    	
    	notificationManager.notify(Constants.NOTIFICATION_ID, notification);
    	
    	
    }
    	
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle data = intent.getExtras();

        if (data != null) {
           // process your notification intent
        }

        // go on with smth else
		if (contentView!=null) {
			contentView=null;
		}

    }	
    
    boolean showingOptions=false;

	@Override
	protected void onUserLeaveHint() {
		super.onUserLeaveHint();

		if (! showingOptions) {
			onBackPressed();
		}
		showingOptions=false;

	}


	//#################################################
	//PREFERENCES
	//#################################################
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//MenuInflater inflater = getMenuInflater();
		//inflater.inflate(R.menu.main, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		//menu.findItem(R.id.connect).setEnabled(fgfs == null);
		//menu.findItem(R.id.disconnect).setEnabled(fgfs != null);
		mostraOpzioni();
		return true;
	}

	


	
	private void mostraOpzioni() {
		showingOptions=true;
		Intent i = new Intent(CountrypowerstationradioActivity.this, Preferences.class);
		startActivityForResult(i,Preferences.PREFERENCES_RESULTCODE);
		// Some feedback to the user
		Toast.makeText(CountrypowerstationradioActivity.this,
			"Here you can enter your settings.",
			Toast.LENGTH_LONG
		).show();
	}
	
	
	
	private void getPrefs() {
		SharedPreferences sharedPreferences = 
			PreferenceManager.getDefaultSharedPreferences(getBaseContext())
		;

		//pv.setMaxDiff(sharedPreferences.getFloat("maxDiff",2));

		//enableSound=sharedPreferences.getBoolean("enableSound", false);
		//sourceTextView.setText(sharedPreferences.getString("address", getString(R.string.defaultRadioLocation)));

		if (myService!=null) {
			myService.setActualRadioLocation(sharedPreferences.getString("address", getString(R.string.defaultRadioLocation)));
		}
		
		
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    
	    if (requestCode==Preferences.PREFERENCES_RESULTCODE && resultCode==Preferences.RESULTCODE_FINISH) {
	    	finish();
	    }
	    
		sistemaBottoni();
	    
	}	
 
	
	
	
	public void onLinkToSiteButtonClick(View v) {
		
		//addCustomNotification();
		//moveTaskToBack(true);

		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.countrypowerstation.net"));
		startActivity(browserIntent);
		
	}

	public void onLinkToSiteCMNButtonClick(View v) {
		
		//addCustomNotification();
		//moveTaskToBack(true);

		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.countrymusicnetwork.it"));
		startActivity(browserIntent);
		
	}

	@Override
	public void volumeChanged(float volume) {
		// TODO Auto-generated method stub
		if (!volumeSeekBarBeingAdjusted) {
	            volumeSeekBar.setProgress((int) (volume*100));
	    } 
	}    
}